/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.jack;

import java.util.Vector;
import javax.microedition.lcdui.ChoiceGroup;
import javax.microedition.lcdui.Image;
import javax.microedition.lcdui.List;

/**
 *
 * @author jack
 */
public class ImageList extends ChoiceGroup {

    private Vector images;

    public ImageList(String title, int listType) {
        super(title, listType);
        images=new Vector();
    }

    public void append(String stringPart) {
        try {
            append(stringPart, stringPart);

        } catch (Exception ex) {
        }
    }

    public void append(String stringPart, String imagePath) {
        try {
            Image image = Image.createImage(Class.class.getResourceAsStream(imagePath));
            images.addElement(imagePath);
            super.append(stringPart, image);
        } catch (Exception ex) {
        }
    }

    /**
     * @return the imagePath
     */
    public String getImagePath() {
        int index=getSelectedIndex();
         if (index > -1) {
            String targetImage = replaceAll((String)images.elementAt(index), "/icons/", "/images/");
            targetImage = replaceAll(targetImage, "_icon", "_image");
            System.out.println("getImagePath: " + targetImage);
            return targetImage;
        } else {
            return "";
        }
    }

    /**
     * @param imagePath the imagePath to set
     */
    public void setImagePath(String imagePath) {
        String targetImage = replaceAll(imagePath, "/images/", "/icons/");
        targetImage = replaceAll(targetImage, "_image", "_icon");
        System.out.println("setImagePath: " + imagePath + "::" + targetImage);
        for (int i = 0; i < size(); i++) {
            if (images.elementAt(i).equals(targetImage)) {
                setSelectedIndex(i, true);
                break;
            }
        }
    }

    private String replaceAll(String str, String oldStr, String newStr) {
        int oldStrLength = oldStr.length();
        StringBuffer dest = new StringBuffer();
        int index = str.indexOf(oldStr);
        if (index == -1) {
            dest.append(str);
        } else {
            dest.append(str.substring(0, index));
        }
        while (index != -1) {
            dest.append(newStr);
            int beforeIndex = index;
            index = str.indexOf(oldStr, index + oldStrLength);
            if (index == -1) {
                dest.append(str.substring(beforeIndex + oldStrLength));
            } else {
                dest.append(str.substring(beforeIndex + oldStrLength, index));
            }
        }
        return dest.toString();
    }
}
